import random
import datetime




from flask import current_app
from flask.ext.migrate import Migrate, MigrateCommand

from info import creat_app, db, models
from flask_script import Manager

# 调用方法获取app对象
from info.models import User
app = creat_app('develop')



manager = Manager(app)

Migrate(app, db)

manager.add_command("db", MigrateCommand)

@manager.option('-u','--username',dest='username')
@manager.option('-p','--password',dest='password')

def createsuperuser(username,password):
    # 创建管理员对象
    admin = User()

    # 设置管理员属性
    admin.mobile = username
    admin.nick_name = username
    admin.password = password
    admin.last_login = datetime.now()
    admin.is_admin = True


    # 添加到数据库
    try:
        # 开启上下文
        with app.app_context():
            db.session.add(admin)
            db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return "创建管理员失败"
    print("管理员创建成功")

# 添加测试数据
def add_test_users():

    # 获取当前时间
    now = datetime.datetime.now()

    # 定义容器
    user_list = []

    # 遍历创建多个用户对象
    for num in range(10,1000):
        # 创建用户对象
        user = User()

        # 设置属性
        user.mobile = "138%08d"%num
        user.nick_name = "138%08d" % num
        user.password_hash = "pbkdf2:sha256:50000$D3z2ZLeS$5e27aac8c9f7d8770e3341e5bcea4cdfeac1008ebfe44f5a60dffb995fe158e6"
        user.is_admin = False

        # 一月以内用户登录（理解成创建时间）的时间
        user.last_login = now - datetime.timedelta(seconds=random.randint(0, 3600 * 24 *31))

        # 添加到列表中
        user_list.append(user)

        print(user.mobile)

    # 添加对象到数据库中
    try:
        with app.app_context():
            db.session.add_all(user_list)
            db.session.commit()
    except Exception as e:
        return "创建失败"

    print("创建添加成功")



if __name__ == '__main__':
    print(app.url_map)
    add_test_users()
    manager.run()